package common.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import common.interf.IDataHandle;
import common.interf.IMyDateHandle;

/**
 * Title:数据操作实现类 Description:把查询出来的数据转换成json或xml格式
 * 
 * @author fieldyang
 * @date 2013-3-12
 * @version 1.0
 */
public class DataHandleImpl implements IDataHandle {
	private IMyDateHandle dateHandle;

	public void setDateHandle(IMyDateHandle dateHandle) {
		this.dateHandle = dateHandle;
	}

	/**
	 * Title:把数据List转换成json或者xml格式的字符串
	 * 
	 * @param inputString
	 *            :field string
	 * @param inputList
	 *            :result list to transfer
	 * @param type
	 *            :xml or json,default is json
	 * @return transfered string
	 */
	public String transferData(String[] fields, String[] formats,
			List inputList, Long total, String type) {
		if (null == type || null == fields || null == inputList)
			return null;

		if (type.trim().equalsIgnoreCase("xml"))
			return toXMLData(fields, formats, inputList, total);
		else
			return toJSONData(fields, formats, inputList, total);

	}

	/**
	 * 生成json串
	 * 
	 * @param fields
	 *            :字段列表
	 * @param inputList
	 *            :输入list
	 * @return 生成的json串
	 */
	private String toJSONData(String[] fields, String[] formats,
			List inputList, Long total) {
		JSONArray jarr = new JSONArray();
		int len = fields.length;
		for (Iterator ite = inputList.iterator(); ite.hasNext();) {
			Object iteO = ite.next();
			Object[] rcd;

			if (len > 1)
				rcd = (Object[]) iteO;
			else
				// 返回单对象处理
				rcd = new Object[] { iteO };

			JSONObject jobj = new JSONObject();
			for (int i = 0; i < len; i++) {
				Object fv = rcd[i];
				if (null == fv)
					continue;
				if (null != formats[i]) // 数据格式
					if ("date".equals(formats[i])) {// 日期格式
						fv = dateHandle.MyStringToISODateString(fv.toString());
					}
				if ("time".equals(formats[i])) { // 时间格式
					fv = dateHandle.MyStringToISODateTimeString(fv.toString());
				}
				jobj.put(fields[i], fv);
			}
			if (!jobj.isEmpty())
				jarr.add(jobj);
		}
		JSONObject jret = new JSONObject();
		if (null != total)
			jret.put("total", total);
		jret.put("rows", jarr);
		return jret.toString();
	}

	/**
	 * 生成xml串
	 * 
	 * @param fields
	 *            :字段列表
	 * @param inputList
	 *            :输入list
	 * @return 生成的xml串
	 */
	private String toXMLData(String[] fields, String[] formats,
			List<Object> inputList, Long total) {
		Document doc = DocumentHelper.createDocument();

		Element root = doc.addElement("ret");

		if (null != total) {
			Element to = root.addElement("total");
			to.setText(String.valueOf(total));
		}
		Element rows = root.addElement("rows");
		int len = fields.length;
		for (Iterator ite = inputList.iterator(); ite.hasNext();) {
			Element row = rows.addElement("row");
			Object[] rcd = (Object[]) ite.next();
			for (int i = 0; i < len; i++) {
				Object fv = rcd[i];
				if (null == fv)
					continue;
				String[] fo = fields[i].split("\\.");
				if (fo.length == 0)
					continue;
				Element el = row.element(fo[0]);
				if (null == el)
					el = row.addElement(fo[0]);
				if (fo.length == 1) {// 简单字段
					el.setText(String.valueOf(fv));
				} else { // 对象字段
					Element el1 = el.addElement(fo[1]);
					el1.setText(String.valueOf(fv));
				}
			}
		}
		return doc.asXML();
	}

	public static Map<String, String> xmlToMap(String xml) {
		System.out.println("xml : " + xml);
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			List<Element> es = root.elements();
			for (Element e : es) {
				String t = e.getText();
				int i1 = t.indexOf("<![CDATA[");
				if (i1 == 0)
					t = t.substring(9, t.length() - 3);
				map.put(e.getName(), t);
			}
		} catch (Exception e) {
		}
		System.out.println("map : " + map);
		return map;
	}

}
